package com.btkjgc.service.impl;

import com.btkjgc.models.*;
import com.btkjgc.service.intf.RoleFunctionService_Intf;
import com.btkjgc.utils.HibernateUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

/**
 * Created by _ESE on 2015/2/6.
 */
@Component
public class RoleFunctionService_Impl implements RoleFunctionService_Intf
{

	@Override
	public int getRoleId(int userid)
	{
		String hql = "from AdminUserRole where userid=" + userid;
		return ((AdminUserRole) HibernateUtil.objectQuery(hql, null))
				.getRoleid();
	}

	@Override
	public int getRoleLevel(int roleid)
	{
		String hql = "from Role where id=" + roleid;
		return ((Role) HibernateUtil.objectQuery(hql, null)).getLevel();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Map<String, Boolean>> getRoleFunction(int roleid)
	{
		String hql0 = "from RoleFunction where roleid=" + roleid;
		List<RoleFunction> rfList = HibernateUtil.executeQuery(hql0, null);
		String hqlF = "from Function where 0=1";
		for (RoleFunction rf : rfList)
		{
			hqlF += " or id=" + rf.getFunction();
		}
		List<Function> functions = HibernateUtil.executeQuery(hqlF, null);

		Map<String, Map<String, Boolean>> roleFunction = new HashMap<String, Map<String, Boolean>>();
		Map<String, Boolean> map = null;

		for (Function temp : functions)
		{
			if (temp == null)
				continue;
			String tempUrl = temp.getUrl();
			if (temp.getPagelevel())
			{// pageLevel
				map = roleFunction.get(tempUrl);
				if (map == null)
				{
					map = new HashMap<String, Boolean>();
					roleFunction.put(tempUrl, map);
				}
			}
			else
			{// functionLevel
				map = roleFunction.get(tempUrl);
				if (map != null)
				{
					map.put(temp.getName(), true);
					roleFunction.put(tempUrl, map);
				}
				else
				{
					map = new HashMap<String, Boolean>();
					roleFunction.put(tempUrl, map);
				}
			}
		}
		// }
		return roleFunction;
	}
}
